<!-- 工单管理 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @row-click="rowClick"
      @on-load="onLoad"
      @select="handSelect"
      @select-all="selectionAll"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          icon="el-icon-edit"
          :disabled="![1, 5].includes(scope.row.status)"
          size="small"
          permission.workorder_edit
          @click.stop="handleEdit(scope.row, scope.index)"
          >编辑
        </el-button>
        <!-- 锁定工单无法进行工单拆分 -->
        <el-button
          type="text"
          icon="el-icon-scissors"
          size="small"
          v-if="permission.workorder_workSplit"
          :disabled="[5].includes(scope.row.status)"
          @click.stop="handleSplit(scope.row, scope.index)"
          >工单拆分</el-button
        >
        <el-button type="text" icon="el-icon-view" size="small" v-if="permission.workorder_view" @click.stop="handleNewView(scope.row, scope.index)">详情</el-button>
      </template>

      <template slot="menuLeft">
        <el-dropdown @command="handleCommand" trigger="click">
          <el-button size="small" icon="el-icon-plus" v-if="permission.workorder_add" type="primary">新增工单<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
          <el-dropdown-menu slot="dropdown" class="orderDropDownMenu">
            <el-dropdown-item command="1">生产工单</el-dropdown-item>
            <el-dropdown-item command="6">改制返工工单</el-dropdown-item>
            <el-dropdown-item command="9">不良返工工单</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.workorder_delete" @click="handleDelete">删 除 </el-button>

        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportExcel.visible = true">导出</el-button>
      </template>
      <template slot-scope="{ row }" slot="routeConfigured">
        <el-tag :class="row.routeConfigured ? 'successTag' : 'dangerTag'">{{ row.routeConfigured ? '是' : '否' }}</el-tag>
      </template>
      <!-- 工单生产数量 -->
      <template slot="planQuantityForm" slot-scope="{ type }">
        <div class="planQuantityAppendRow">
          <el-input-number
            :disabled="defaults.planQuantity.disabled"
            controls-position="right"
            :min="1"
            placeholder="请输入工单生产数量"
            v-model="form.planQuantity"
            class="input-with-select"
          >
          </el-input-number>
        </div>
      </template>
    </avue-crud>

    <!-- 新增、编辑 -->
    <el-dialog
      custom-class="addDialog"
      append-to-body
      :close-on-click-modal="false"
      :title="addDialog.title"
      :visible.sync="addDialog.visible"
      :before-close="handleAddDialogReset"
      @open="handleAddOpen"
      width="80%"
    >
      <avue-form
        :key="reload"
        ref="addFormRef"
        v-model="addDialog['form' + addDialog.headerForm.type]"
        :option="addDialog['option' + addDialog.headerForm.type]"
        @submit="handleAddSubmit"
        @reset-change="handleAddReset"
      >
        <template slot="orderNo" v-if="addDialog['form' + addDialog.headerForm.type]">
          <avue-input v-model="addDialog['form' + addDialog.headerForm.type].orderNo" :disabled="addDialog.title.includes('编辑')" placeholder="请输入返工工单号" />
        </template>
      </avue-form>

      <span slot="footer" class="avue-dialog__footer">
        <el-button size="small" icon="el-icon-circle-close" class="cancelWorkOrderBtn" @click="handleAddDialogReset">取消</el-button>
        <el-button size="small" type="primary" class="addWorkOrderBtn" icon="el-icon-circle-plus-outline" v-preventReClick @click="handleAddDialogSubmit">保存</el-button>
      </span>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog
      custom-class="detailDialog"
      append-to-body
      :close-on-click-modal="false"
      title="详情"
      width="80%"
      :visible.sync="detailDialog.visible"
      :before-close="handleCloseDetailDialog"
    >
      <div class="avue-group__header avue-group">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h1 class="avue-group__title">工单信息</h1>
      </div>
      <avue-form ref="editRef" v-model="detailDialog.form" :option="detailDialog.option"> </avue-form>
    </el-dialog>

    <SubWorkOrder ref="subworkorder" @closeSubWorkOrderDialog="closeSubWorkOrderDialog" />

    <!-- 物料基础数据 弹框 -->
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <export-comp ref="exportExcel" page-api-url="mes-product/work-order/page" file-name="工单管理" :option="option" :page="page" :query="query"></export-comp>
    <importDialogComp
      acceptDesc="仅能导入工单类型为“生产工单”的工单，请上传.xls,.xlsx标准格式文件"
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    >
    </importDialogComp>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, remove } from '@/api/product/workorder';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import exportComp from '@/components/export-comp';
import importDialogComp from '@/components/dialog/import/index.vue';

import SubWorkOrder from '@/views/product/components/subWorkOrder.vue';
import { mapGetters, mapState } from 'vuex';

import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import userWorkorder from '@/mixins/workorder';

import { baseDetailColumns, badWorkDetailColumns, restWorkDetailColumns } from '@/views/product/data/workorder.js';
export default {
  name: 'workorder',
  components: {
    GlobalModalTemplate,
    SubWorkOrder,
    userTableConfig,
    importDialogComp,
    exportComp
  },
  mixins: [userConfig(), userWorkorder()],
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      reload: Math.random(),
      pageCode: 'WORKERDER',
      rowId: null,
      isLockRow: false,
      partMasterId: '',
      firstToEdit: true,
      visibile: false,
      form: {},
      query: {},
      search: {},
      defaults: {},
      loading: true,
      data: [],
      baseDetailColumns: baseDetailColumns,
      restWorkDetailColumns: restWorkDetailColumns, //改制返工详情
      badWorkDetailColumns: badWorkDetailColumns, // 不良返工详情
      addDialog: {
        visible: false,
        loading: false,
        title: '新增生产工单',
        headerForm: {},
        form1: {},
        form2: {},
        form3: {},
        form4: {},
        form5: {},
        form6: {},
        form7: {},
        form8: {},
        form9: {}
      },
      detailDialog: {
        visible: false,
        form: {},
        loading: false,
        tableData: [],
        tableOption: {
          height: 250,
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 5,
          border: true,
          index: true,
          indexLabel: '序号',
          addBtn: false,
          viewBtn: false,
          viewTitle: '详情',
          editBtn: false,
          delBtn: false,
          selection: false,
          dialogClickModal: false,
          menu: false,
          labelWidth: 160,
          searchLabelWidth: 100,
          dialogDrag: true,
          highlightCurrentRow: true,
          columnBtn: false,
          column: [
            { prop: 'appendQuantity', label: '追加数量' },
            { prop: 'appendReason', label: '追加原因' },
            { prop: 'name', label: '追加人员' },
            { prop: 'time', label: '追加时间' }
          ]
        },
        option: {
          submitBtn: false,
          emptyBtn: false,
          detail: true,
          labelWidth: 150,
          column: baseDetailColumns
        }
      },
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/workorder/import',
        exportName: '工单管理导入模版.xlsx',
        title: '工单管理导入'
      },
      commonDialog: {
        dispatch: true
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 18,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        viewTitle: '详情',
        editBtn: false,
        delBtn: false,
        addBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: true,
        menuWidth: 200,
        labelWidth: 160,
        searchLabelWidth: 100,
        dialogDrag: true,
        highlightCurrentRow: true,
        columnBtn: false
      },
      // 1：待排程；2：待生产；3：生产中；4：完工；5：锁定；6：强制完工;
      selectionList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workorder_add, false),
        viewBtn: this.vaildData(this.permission.workorder_view, false),
        delBtn: this.vaildData(this.permission.workorder_delete, false),
        editBtn: this.vaildData(this.permission.workorder_edit, false),
        appendBtn: this.vaildData(this.permission.workorder_append, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    // 正向追溯跳转
    let urlQuery = this.$route.query;
    if (urlQuery && urlQuery.workOrderNo) {
      this.search.orderNo = urlQuery.workOrderNo;
      this.query.orderNo = urlQuery.workOrderNo;
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    handleCommand(command) {
      this.handleAdd(command);
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleEdit(row, index) {
      this.firstToEdit = true;
      this.rowId = row.id;
      this.isLockRow = row.status === 5; // 工单状态为锁定时 isLockRow:true
      this.addDialog.headerForm.type = row.type;
      const formOrderType = 'form' + this.addDialog.headerForm.type;
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.addDialog[formOrderType] = structuredClone(data);
        if (this.addDialog.headerForm.type != 1) {
          this.addDialog[formOrderType]['productTotal'] = data.originalQuantity;
        }
      });
      this.addDialog.visible = true;
      switch (row.type) {
        case '1':
          this.addDialog.title = '编辑生产工单';
          break;
        case '6':
          this.addDialog.title = '编辑改制返工工单';
          break;
        case '9':
          this.addDialog.title = '编辑不良返工工单';
          break;
        default:
          this.addDialog.title = '编辑';
          break;
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isDelete = this.selectionList.every((s) => s.status == 1);
      if (!isDelete) {
        this.$message.warning('当前勾选数据中存在非待排程状态，请仔细检查');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = this.selectionList.map((s) => s.id);
          return remove(ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleSplit(row, index) {
      if (row.splitType == 1 && row.status != 1) {
        this.$message.warning('按数量拆分的，只有待排程状态下才能拆分,请选择其它工单');
        return;
      }
      this.$refs.subworkorder.open(row.id);
    },
    beforeClose(done, type) {
      this.onLoad(this.page);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.datetimerange) {
        params.planEndDate = params.datetimerange + ' ' + '00:00:00';
        delete params.datetimerange;
      }
      if (params.type) {
        params.workOrderType = params.type;
        delete params.type;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          // 前端排序
          this.data = data.records;
          this._forEach(this.data, (item) => {
            if (item.extFields) {
              let extFields = JSON.parse(item.extFields || '{}');
              item.extFieldsOperationName = extFields.operation_name;
            }
          });
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openUserCommonModal(params) {
      let { type, value, subIndex } = params;
      const formOrderType = 'form' + this.addDialog.headerForm.type;
      this.subWorkOrderIndex = subIndex;
      if (this.isLockRow) {
        this.$message.warning('当前工单已锁定');
        return false;
      }
      switch (type) {
        // 客户名称
        case 'partnerName':
          this.modalName = 'partnerNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择客户信息（双击进行选择）',
            url: '/api/mes-admin/customer/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            templateName: 'PARTNER'
          };
          break;
        // 生产订单
        case 'productionOrderNo':
          this.modalName = 'productionOrderNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择生产订单信息（双击进行选择）',
            url: '/api/mes-product/production-order/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'PRODUCTION_ORDER_NO'
          };
          break;
        // 产品编码
        case 'productCode':
          this.modalName = 'partmasterModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90
          };
          // if (this.addDialog[formOrderType].productionOrderNo) {
          //   this.tableOption.url = '/api/mes-admin/partmaster/list-pre-part';
          //   this.tableOption.isPage = false;
          //   this.tableOption.query = {
          //     partId: this.partMasterId
          //   };
          //   this.tableOption.templateName = 'WORKPARTMASTER';
          // } else {
          this.tableOption.url = '/api/mes-admin/part-master/page';
          this.tableOption.isPage = true;
          this.tableOption.query = { semifinished: true };
          this.tableOption.templateName = 'NOWORKPARTMASTER';
          // }
          break;
        // 原始工单
        case 'originalWorkOrderNo':
          this.modalName = 'originalWorkOrderNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择工单信息（双击进行选择）',
            url: '/api/mes-product/work-order/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'WORKORDER'
          };
          break;
        // 改制后产品编码
        case 'oldAfterpartNo':
          this.modalName = 'oldAfterpartNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            url: '/api/mes-admin/part-master/page',
            isPage: true,
            query: {
              semifinished: true
            },
            templateName: 'NOWORKPARTMASTER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      const formOrderType = 'form' + this.addDialog.headerForm.type;
      switch (this.modalName) {
        case 'partnerNameModal':
          this.batchSetField(
            [
              { key: 'customerName', value: 'name' },
              { key: 'customerCode', value: 'code' },
              { key: 'customerId', value: 'id' }
            ],
            rowData
          );
          break;
        case 'productionOrderNoModal':
          this.partMasterId = this._get(rowData, 'partMasterId', '');
          this.batchSetField(
            [
              { key: 'productionOrderNo', value: 'productionOrderNo' },
              { key: 'productionOrderId', value: 'id' },
              { key: 'salesOrderNo', value: 'salesOrderNo' },
              { key: 'partMasterId', value: '' },
              { key: 'partNo', value: '' },
              { key: 'partName', value: '' }
            ],
            rowData
          );
          break;
        case 'partmasterModal':
          if (this.addDialog[formOrderType].productionOrderNo) {
            this.batchSetField(
              [
                { key: 'productPartName', value: 'partName' },
                { key: 'productPartId', value: 'partId' }
              ],
              rowData
            );
          } else {
            this.batchSetField(
              [
                { key: 'productPartName', value: 'name' },
                { key: 'productPartId', value: 'id' }
              ],
              rowData
            );
          }
          this.batchSetField(
            [
              { key: 'productPartNo', value: 'partNo' },
              { key: 'productPartModel', value: 'partModel' }
            ],
            rowData
          );
          break;
        case 'originalWorkOrderNoModal':
          if (this.addDialog.headerForm.type == 6) {
            this.batchSetField(
              [
                { key: 'originalWorkOrderId', value: 'id' },
                { key: 'originalWorkOrderNo', value: 'workOrderNo' },
                { key: 'productionOrderNo', value: 'productionOrderNo' },
                { key: 'productionOrderId', value: 'productionOrderId' },
                { key: 'salesOrderNo', value: 'salesOrderNo' },
                { key: 'lotNo', value: 'lotNo' },
                { key: 'bomId', value: 'bomId' },
                { key: 'bomVersion', value: 'bomVersion' },
                { key: 'originalProductPartNo', value: 'productPartNo' },
                { key: 'originalProductPartName', value: 'productPartName' },
                { key: 'originalProductPartModel', value: 'productPartModel' },
                { key: 'originalPlanQuantity', value: 'planQuantity' }
              ],
              rowData
            );
          }
          if (this.addDialog.headerForm.type == 9) {
            this.batchSetField(
              [
                { key: 'originalWorkOrderId', value: 'id' },
                { key: 'originalWorkOrderNo', value: 'workOrderNo' },
                { key: 'productionOrderNo', value: 'productionOrderNo' },
                { key: 'productionOrderId', value: 'productionOrderId' },
                { key: 'salesOrderNo', value: 'salesOrderNo' },
                { key: 'lotNo', value: 'lotNo' },
                { key: 'bomId', value: 'bomId' },
                { key: 'bomVersion', value: 'bomVersion' },
                { key: 'productPartNo', value: 'productPartNo' },
                { key: 'productPartName', value: 'productPartName' },
                { key: 'productPartModel', value: 'productPartModel' },
                { key: 'productPartId', value: 'productPartId' },
                { key: 'originalPlanQuantity', value: 'planQuantity' }
              ],
              rowData
            );
          }
          break;
        case 'oldAfterpartNoModal':
          this.batchSetField(
            [
              { key: 'productPartName', value: 'name' },
              { key: 'productPartNo', value: 'partNo' },
              { key: 'productPartModel', value: 'partModel' },
              { key: 'productPartId', value: 'id' }
            ],
            rowData
          );
          break;
        default:
          break;
      }
    },
    batchSetField(data, rowData) {
      const formOrderType = 'form' + this.addDialog.headerForm.type;
      for (const item of data) {
        this.$set(this.addDialog[formOrderType], item.key, this._get(rowData, item.value, ''));
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    rowClick(row, column) {
      this.$util.table.rowClick(this.$refs.crud, row, this.selectionList);
    },
    handSelect() {
      this.$refs.crud.setCurrentRow();
    },
    selectionAll() {
      this.$refs.crud.setCurrentRow();
    },
    closeSubWorkOrderDialog(params) {
      if (params) {
        this.onLoad(this.page);
        this.$refs.crud.toggleSelection();
      }
    },

    handleImport() {
      this.importConfig.show = true;
    },
    codeClose(value) {
      if (value) {
        this.onLoad(this.page);
      }
    },
    handleNewView(row, index) {
      switch (row.type) {
        // 改制返工工单
        case '6':
          this.detailDialog.option.column = this.restWorkDetailColumns;
          break;
        // 不良返工工单
        case '9':
          this.detailDialog.option.column = this.badWorkDetailColumns;
          break;
        default:
          this.detailDialog.option.column = this.baseDetailColumns;
          break;
      }
      this.detailDialog.visible = true;
      this.detailDialog.loading = true;
      getDetail(row.id)
        .then((res) => {
          this.detailDialog.form = JSON.parse(JSON.stringify(res.data.data));
        })
        .finally(() => {
          this.detailDialog.loading = false;
        });
    },
    handleAddOpen() {
      this.reload = Math.random();
    },
    handleAddDialogSubmit() {
      this.$refs.addFormRef.submit();
    },
    handleAddDialogReset() {
      this.$refs.addFormRef.resetForm();
    },
    handleAddSubmit(form, done, loading) {
      const formOrderType = 'form' + this.addDialog.headerForm.type;
      this.addDialog[formOrderType].type = this.addDialog.headerForm.type;
      if (this.addDialog.title.includes('新增')) {
        delete this.addDialog[formOrderType].id;
      }
      console.log(this.addDialog[formOrderType], 'this.addDialog[formOrderType]');
      add(this.addDialog[formOrderType]).then(
        () => {
          this.addDialog.visible = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.addFormRef.resetForm();
          done();
        },
        () => {
          loading();
        }
      );
    },
    handleAddReset() {
      this.addDialog.visible = false;
    },
    resetForm(formType, fields) {
      Object.keys(fields).forEach((key) => {
        this.$set(this.addDialog[formType], key, fields[key]);
      });
    },
    handleAdd(value) {
      const validOrderTypes = [6, 9];
      if (validOrderTypes.includes(value) && this.selectionList.length > 1) {
        this.$message.warning('只能选择一条数据进行新增改制返工工单或新增不良返工工单操作');
        return false;
      }

      this.addDialog.visible = true;
      this.$set(this.addDialog.headerForm, 'type', value);

      const dialogTitles = {
        1: '新增生产工单',
        6: '新增改制返工工单',
        9: '新增不良返工工单'
      };
      this.addDialog.title = dialogTitles[value];

      const formOrderType = `form${this.addDialog.headerForm.type}`;

      // 系统登录账号自动带出 制定人
      // this.resetForm(formOrderType, { creatorName: this.realName, createUserId: this.userId });

      // 当勾选一条数据时, 新增改制返工工单或新增不良返工工单,直接带出勾选工单信息
      if (this.selectionList.length == 1) {
        const data = this.selectionList[0];
        const commonFields = {
          originalWorkOrderNo: data.orderNo,
          originalWorkOrderId: data.id,
          productionOrderNo: data.productionOrderNo,
          productionOrderId: data.productionOrderId,
          salesOrderNo: data.salesOrderNo,
          bomId: data.bomId,
          bomVersion: data.bomVersion,
          partMasterId: data.partMasterId,
          partnerCode: data.partnerCode,
          partnerId: data.partnerId,
          productTotal: data.planQuantity,
          productModel: data.productModel,
          lotNo: data.lotNo
        };
        let additionalFields;
        if (value == 6) {
          // 改制返工工单
          additionalFields = {
            originalPartNo: data.partNo,
            originalPartName: data.partName,
            originalPartModel: data.partModel
          };
        } else if (value == 9) {
          additionalFields = {
            partNo: data.partNo,
            partName: data.partName,
            partModel: data.partModel
          };
        }
        this.resetForm(formOrderType, { ...commonFields, ...additionalFields });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.planQuantityAppendRow {
  display: flex;
  justify-content: space-between;
  .input-with-select {
    flex: 1;
  }
}

::v-deep .detailDialog {
  margin-top: 5vh !important;
  .el-dialog__body {
    padding: 0 20px 20px;
  }
  .avue-form__menu--right {
    display: none;
  }
  .avue-crud__menu {
    display: none;
  }
}
::v-deep .addDialog {
  .add-header-form {
    .avue-form__menu {
      display: none;
    }
  }
}
</style>
